import { useState, useEffect } from 'react';
import { LLMConfigComponent, BrowserConfigComponent, SearchConfigComponent, LLMConfig, BrowserConfig, SearchConfig } from '../components/Settings';
import { useToast } from '../components/Toast';
import { getConfig, saveConfig } from '../services/configService';

export const Settings = () => {
  const [saveStatus, setSaveStatus] = useState<'idle' | 'saving' | 'success' | 'error'>('idle');
  const [activeTab, setActiveTab] = useState<'llm' | 'browser' | 'search'>('llm');
  const toast = useToast();
  const [formErrors, setFormErrors] = useState<{
    llm: boolean;
    browser: boolean;
    search: boolean;
  }>({
    llm: false,
    browser: false,
    search: false
  });

  // 默认LLM配置
  const [llmConfig, setLlmConfig] = useState<LLMConfig>({
    base_url: 'https://api.deepseek.com/v1',
    api_key: '',
    model: 'deepseek-chat',
    temperature: 0,
    max_tokens: 4086
  }); 

  // 默认浏览器配置
  const [browserConfig, setBrowserConfig] = useState<BrowserConfig>({
    headless: false,
    disable_security: true,
    chrome_instance_path: '',
    proxy_enabled: false,
    proxy: {
      server: '',
      username: '',
      password: ''
    }
  });

  // 默认搜索配置
  const [searchConfig, setSearchConfig] = useState<SearchConfig>({
    engine: 'Baidu',
    max_retries: 3,
    retry_delay: 60,
  });

  // 加载配置
  useEffect(() => {
    const loadConfig = async () => {
      try {
        const response = await getConfig();
        if (response.status === 'exists') {
          const { llm, browser, search } = response.config;
          // console.log("aaaa",llm)
          if (llm) setLlmConfig(llm);
          if (browser) setBrowserConfig(browser);
          if (search) setSearchConfig(search);
          // 在加载完成后验证
          setFormErrors({
            llm: !validateLLMConfig(llm),
            browser: !validateBrowserConfig(browser),
            search: !validateSearchConfig(search)
          });
        }
      } catch (error) {
        console.error('加载配置失败:', error);
        toast.error('加载失败', '无法加载配置信息，将使用默认配置。');
      }
    };
    
    loadConfig();
  }, []);

  // 检验LLM配置
  const validateLLMConfig = (config: LLMConfig): boolean => {
    if (!config.base_url.trim()) return false;
    try {
      new URL(config.base_url);
    } catch (e) {
      return false; 
    }
    
    if (!config.api_key.trim() || config.api_key.length < 8) return false;
    if (config.temperature < 0 || config.temperature > 10) return false;
    if (config.max_tokens <= 0 || config.max_tokens > 8192) return false;
    if (!config.model) return false;
    
    return true;
  };

  // 检验浏览器配置
  const validateBrowserConfig = (config: BrowserConfig): boolean => {
    // 如果启用了代理，验证代理配置
    if (config.proxy_enabled && config.proxy) {
      // 验证代理服务器地址
      if (!config.proxy.server.trim()) return false;
      try {
        new URL(config.proxy.server);
      } catch (e) {
        // 如果不是有效的URL，检查是否包含端口号
        if (!config.proxy.server.includes(':')) return false;
      }
    }
    
    return true;
  };

  // 检验搜索配置
  const validateSearchConfig = (config: SearchConfig): boolean => {
    if (!config.engine) return false;
    if (config.max_retries < 0 || config.max_retries > 10) return false;
    if (config.retry_delay < 1 || config.retry_delay > 300) return false;
    
    return true;
  };

  // 更新LLM配置
  const handleLLMConfigChange = (config: LLMConfig) => {
    setLlmConfig(config);
    setFormErrors(prev => ({
      ...prev,
      llm: !validateLLMConfig(config)
    }));
  };

  // 更新浏览器配置
  const handleBrowserConfigChange = (config: BrowserConfig) => {
    setBrowserConfig(config);
    setFormErrors(prev => ({
      ...prev,
      browser: !validateBrowserConfig(config)
    }));
  };

  // 更新搜索配置
  const handleSearchConfigChange = (config: SearchConfig) => {
    setSearchConfig(config);
    setFormErrors(prev => ({
      ...prev,
      search: !validateSearchConfig(config)
    }));
  };

  // 保存设置
  const handleSave = async () => {
    // 根据当前标签检查表单验证状态
    let hasErrors = false;
    
    switch (activeTab) {
      case 'llm':
        hasErrors = formErrors.llm;
        break;
      case 'browser':
        hasErrors = formErrors.browser;
        break;
      case 'search':
        hasErrors = formErrors.search;
        break;
    }
    
    if (hasErrors) {
      toast.error(
        '验证错误', 
        '请修复表单中的错误后再保存设置。'
      );
      return;
    }
    
    setSaveStatus('saving');
    
    try {
      const config = {
        llm: llmConfig,
        browser: browserConfig,
        search: searchConfig
      };
      
      const response = await saveConfig(config);
      
      if (response.status === 'success') {
        setSaveStatus('success');
        
        // 根据当前活动的标签显示不同的消息
        let successTitle, successMessage;
        switch (activeTab) {
          case 'llm':
            successTitle = 'LLM设置已保存';
            successMessage = 'LLM配置已成功更新。';
            break;
          case 'browser':
            successTitle = '浏览器设置已保存';
            successMessage = '浏览器配置已成功更新。';
            break;
          case 'search':
            successTitle = '搜索设置已保存';
            successMessage = '搜索配置已成功更新。';
            break;
        }
        
        toast.success(successTitle, successMessage);
      } else {
        throw new Error('保存失败');
      }
    } catch (error) {
      console.error('保存配置失败:', error);
      setSaveStatus('error');
      toast.error('保存失败', '无法保存配置信息，请稍后重试。');
    } finally {
      // 重置状态
      setTimeout(() => {
        setSaveStatus('idle');
      }, 3000);
    }
  };

  return (
    <div className="container mx-auto py-8 px-4">
          <div className="flex justify-between items-center mb-6">
            <h1 className="text-2xl font-bold dark:text-white">设置</h1>
            
            {saveStatus === 'saving' && (
              <div className="text-blue-600">保存中...</div>
            )}
            
            {saveStatus === 'success' && (
              <div className="text-green-600">✓ 设置已保存</div>
            )}
            
            {saveStatus === 'error' && (
              <div className="text-red-600">❌ 保存失败</div>
            )}
          </div>
          
          <div className="bg-white dark:bg-gray-800 rounded-lg shadow-md overflow-hidden">
            {/* 选项卡导航 */}
            <div className="flex border-b border-gray-200 dark:border-gray-700">
              <button
                className={`py-4 px-6 text-sm font-medium ${
                  activeTab === 'llm' 
                    ? 'text-blue-600 dark:text-blue-400 border-b-2 border-blue-600 dark:border-blue-400' 
                    : 'text-gray-500 dark:text-gray-400 hover:text-gray-700 dark:hover:text-gray-300'
                }`}
                onClick={() => setActiveTab('llm')}
              >
                LLM 配置
              </button>
              <button
                className={`py-4 px-6 text-sm font-medium ${
                  activeTab === 'browser' 
                    ? 'text-blue-600 dark:text-blue-400 border-b-2 border-blue-600 dark:border-blue-400' 
                    : 'text-gray-500 dark:text-gray-400 hover:text-gray-700 dark:hover:text-gray-300'
                }`}
                onClick={() => setActiveTab('browser')}
              >
                浏览器配置
              </button>
              <button
                className={`py-4 px-6 text-sm font-medium ${
                  activeTab === 'search' 
                    ? 'text-blue-600 dark:text-blue-400 border-b-2 border-blue-600 dark:border-blue-400' 
                    : 'text-gray-500 dark:text-gray-400 hover:text-gray-700 dark:hover:text-gray-300'
                }`}
                onClick={() => setActiveTab('search')}
              >
                搜索配置
              </button>
            </div>
            
            {/* 内容区域 */}
            <div className="p-6 dark:text-white">
              {activeTab === 'llm' ? (
                <LLMConfigComponent 
                  config={llmConfig} 
                  onChange={handleLLMConfigChange} 
                />
              ) : activeTab === 'browser' ? (
                <BrowserConfigComponent 
                  config={browserConfig} 
                  onChange={handleBrowserConfigChange} 
                />
              ) : (
                <SearchConfigComponent 
                  config={searchConfig} 
                  onChange={handleSearchConfigChange} 
                />
              )}
              
              {/* 底部操作按钮 */}
              <div className="flex justify-between mt-8 pt-4 border-t border-gray-200 dark:border-gray-700">
                <div>
                  {activeTab === 'llm' && formErrors.llm && (
                    <p className="text-sm text-red-500">请修复LLM配置中的错误</p>
                  )}
                  {activeTab === 'browser' && formErrors.browser && (
                    <p className="text-sm text-red-500">请修复浏览器配置中的错误</p>
                  )}
                  {activeTab === 'search' && formErrors.search && (
                    <p className="text-sm text-red-500">请修复搜索配置中的错误</p>
                  )}
                </div>
                <button
                  onClick={handleSave}
                  disabled={
                    (activeTab === 'llm' && formErrors.llm) ||
                    (activeTab === 'browser' && formErrors.browser) ||
                    (activeTab === 'search' && formErrors.search)
                  }
                  className={`px-6 py-2 text-white rounded-md flex items-center ${
                    (activeTab === 'llm' && formErrors.llm) ||
                    (activeTab === 'browser' && formErrors.browser) ||
                    (activeTab === 'search' && formErrors.search)
                      ? 'bg-gray-400 cursor-not-allowed'
                      : 'bg-blue-600 hover:bg-blue-700'
                  }`}
                >
                  <span className="mr-1">💾</span>
                  保存更改
                </button>
              </div>
            </div>
          </div>
    </div>
  );
}; 
